<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>okChat-聊天列表</title>
    <style>
        body {
            font-family: "微软雅黑";
            font-size: 12px;
        }

        .chatDiv {
            width: 300px;
            height: 200px;
            border: 1px solid black;
            overflow: auto;
        }
    </style>
</head>
<body>
    <p id="tip"></p>
    <p>当前用户：<span id="username"></span></p>
    <p>聊天列表：</p>
    <ul id="chatListUl"></ul>
    <p>你当前正在和【<span id="currentChatUsername"></span>】聊天！</p>
    <div class="chatDiv">
    </div>
    <input type="text" autocomplete="off" id="message">
    <button id="sendMessage">发送</button>
    <script src="jquery-3.4.1.min.js"></script>
    <script>
        $(function () {

            /************************************************************/
            let webSocket = new WebSocket("ws://127.0.0.1:8088/websocket");
            webSocket.onopen = function () {
                $("#tip").text("WebSocket连接成功");
            };
            webSocket.onclose = function () {
                $("#tip").text("WebSocket连接关闭");
            };
            webSocket.onerror = function () {
                $("#tip").text("WebSocket发生错误");
            };
            webSocket.onmessage = function (e) {
                console.log("WebSocket接收到消息：" + e.data);
            };
            /************************************************************/

            let username = sessionStorage.getItem("username");
            $("#username").text(username);

            let chatList = ["zhangsan", "lisi", "wangwu", "zhaoliu", "sunqi"];
            for (let i = 0; i < chatList.length; i++) {
                if (chatList[i] === username) {
                    continue;
                }
                $("#chatListUl").append("<li>" + chatList[i] + "</li>");
            }

            $("#chatListUl li").click(function () {
                let friendUsername = $(this).text();
                $("#currentChatUsername").text(friendUsername);
                $(".chatDiv").empty();
            });

            $("#sendMessage").click(function () {
                let message = $("#message").val().trim();
                if (message === "") {
                    alert("请输入内容");
                    return;
                }
                $(".chatDiv").append("<div>我：" + message + "</div>");
                webSocket.send(message);
            });
        });
    </script>
</body>
</html>
